package com.beemans.corekit.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.anythink.nativead.api.ATNativeImageView;
import com.anythink.nativead.api.ATNativeMaterial;
import com.anythink.nativead.api.ATNativePrepareExInfo;
import com.beemans.corekit.R;
import com.beemans.corekit.integration.topon.INativeSelfRender;

import java.util.ArrayList;
import java.util.List;

/**
 * @noinspection ClassCanBeRecord
 */
public class CustomNativeRender implements INativeSelfRender {
    @NonNull
    private final View selfRenderView;

    public CustomNativeRender(@NonNull View selfRenderView) {
        this.selfRenderView = selfRenderView;
    }

    @Override
    public void onBindView(
            @NonNull Context context,
            @NonNull ATNativeMaterial atNativeMaterial,
            @NonNull ATNativePrepareExInfo atNativePrepareInfo
    ) {
        selfRenderView.setVisibility(View.VISIBLE);

        final TextView tvFlFullClick = selfRenderView.findViewById(R.id.nativeSelf_tvFullClick);
        final TextView titleView = selfRenderView.findViewById(R.id.nativeSelf_tvAdTitle);
        final TextView descView = selfRenderView.findViewById(R.id.nativeSelf_tvAdDesc);
        final TextView ctaView = selfRenderView.findViewById(R.id.nativeSelf_tvInstall);
        final TextView adFromView = selfRenderView.findViewById(R.id.nativeSelf_tvAdFrom);
        final FrameLayout iconArea = selfRenderView.findViewById(R.id.nativeSelf_flAdImage);
        final FrameLayout contentArea = selfRenderView.findViewById(R.id.nativeSelf_flAdContentArea);
        final ATNativeImageView logoView = selfRenderView.findViewById(R.id.nativeSelf_ivAdLogoPlatform);
        final ImageView ivClose = selfRenderView.findViewById(R.id.nativeSelf_ivClose);

        final List<View> clickViewList = new ArrayList<>();

        // close btn
        if (ivClose != null) {
            atNativePrepareInfo.setCloseView(ivClose);
        }

        // title
        final String title = atNativeMaterial.getTitle();
        if (!TextUtils.isEmpty(title)) {
            titleView.setText(title);
            atNativePrepareInfo.setTitleView(tvFlFullClick);
            clickViewList.add(tvFlFullClick);
            titleView.setVisibility(View.VISIBLE);
        } else {
            titleView.setVisibility(View.GONE);
        }

        // desc
        final String descriptionText = atNativeMaterial.getDescriptionText();
        if (!TextUtils.isEmpty(descriptionText)) {
            descView.setText(descriptionText);
            atNativePrepareInfo.setDescView(descView);
            clickViewList.add(descView);
            descView.setVisibility(View.VISIBLE);
        } else {
            descView.setVisibility(View.GONE);
        }

        // icon（某些平台必须添加）
        final View adIconView = atNativeMaterial.getAdIconView();
        final String iconImageUrl = atNativeMaterial.getIconImageUrl();
        iconArea.removeAllViews();

        if (adIconView != null) {
            final ViewParent viewParent = adIconView.getParent();
            if (viewParent instanceof ViewGroup) {
                ((ViewGroup) viewParent).removeView(adIconView);
            }
            iconArea.addView(adIconView);
            atNativePrepareInfo.setIconView(adIconView);
            clickViewList.add(adIconView);
            iconArea.setVisibility(View.VISIBLE);
        } else if (!TextUtils.isEmpty(iconImageUrl)) {
            final ATNativeImageView iconView = new ATNativeImageView(context);
            iconArea.addView(iconView);
            iconView.setImage(iconImageUrl);
            atNativePrepareInfo.setIconView(iconView);
            clickViewList.add(iconView);
            iconArea.setVisibility(View.VISIBLE);
        } else {
            iconArea.setVisibility(View.INVISIBLE);
        }

        // cta button
        final String callToActionText = atNativeMaterial.getCallToActionText();
        if (!TextUtils.isEmpty(callToActionText)) {
            ctaView.setText(callToActionText);
            atNativePrepareInfo.setCtaView(ctaView);
            clickViewList.add(ctaView);
            ctaView.setVisibility(View.VISIBLE);
        } else {
            ctaView.setVisibility(View.GONE);
        }

        // media view（某些平台必须添加）
        final View mediaView = atNativeMaterial.getAdMediaView(contentArea);
        final int mainImageWidth = atNativeMaterial.getMainImageWidth();
        final int mainImageHeight = atNativeMaterial.getMainImageHeight();

        onViewGlobalLayout(contentArea, () -> {
            final int realMainImageHeight = contentArea.getHeight();
            final FrameLayout.LayoutParams mainImageParam = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT
            );

            if (mainImageHeight > 0 && mainImageWidth > mainImageHeight) {
                final int realMainImageWidth = realMainImageHeight * mainImageWidth / mainImageHeight;
                final int containerWidth = selfRenderView.getWidth();

                if (realMainImageWidth <= containerWidth) {
                    mainImageParam.width = realMainImageWidth;
                    mainImageParam.height = realMainImageHeight;
                } else {
                    mainImageParam.width = containerWidth;
                    mainImageParam.height = FrameLayout.LayoutParams.WRAP_CONTENT;
                }
            } else {
                if (mainImageHeight > 0) {
                    mainImageParam.width = realMainImageHeight * mainImageWidth / mainImageHeight;
                } else {
                    mainImageParam.width = FrameLayout.LayoutParams.WRAP_CONTENT;
                }
                mainImageParam.height = realMainImageHeight;
            }

            contentArea.removeAllViews();

            if (mediaView != null) {
                final ViewParent viewParent = mediaView.getParent();
                if (viewParent instanceof ViewGroup) {
                    ((ViewGroup) viewParent).removeView(mediaView);
                }
                mainImageParam.gravity = Gravity.CENTER;
                mediaView.setLayoutParams(mainImageParam);
                contentArea.addView(mediaView, mainImageParam);
                clickViewList.add(mediaView);
                contentArea.setVisibility(View.VISIBLE);
            } else if (!TextUtils.isEmpty(atNativeMaterial.getMainImageUrl())) {
                final ATNativeImageView imageView = new ATNativeImageView(context);
                imageView.setImage(atNativeMaterial.getMainImageUrl());
                imageView.setLayoutParams(mainImageParam);
                contentArea.addView(imageView, mainImageParam);
                atNativePrepareInfo.setMainImageView(imageView);
                clickViewList.add(imageView);
                contentArea.setVisibility(View.VISIBLE);
            } else {
                contentArea.removeAllViews();
                contentArea.setVisibility(View.GONE);
            }
        });

        // ad logo
        final String adChoiceIconUrl = atNativeMaterial.getAdChoiceIconUrl();
        final Bitmap adLogoBitmap = atNativeMaterial.getAdLogo();
        if (!TextUtils.isEmpty(adChoiceIconUrl)) {
            logoView.setImage(adChoiceIconUrl);
            atNativePrepareInfo.setAdLogoView(logoView);
            clickViewList.add(logoView);
            logoView.setVisibility(View.VISIBLE);
        } else if (adLogoBitmap != null) {
            logoView.setImageBitmap(adLogoBitmap);
            clickViewList.add(logoView);
            logoView.setVisibility(View.VISIBLE);
        } else {
            logoView.setImageBitmap(null);
            logoView.setVisibility(View.GONE);
        }

        // ad from
        final String adFrom = atNativeMaterial.getAdFrom();
        if (!TextUtils.isEmpty(adFrom)) {
            adFromView.setText(adFrom);
            clickViewList.add(adFromView);
            adFromView.setVisibility(View.VISIBLE);
        } else {
            adFromView.setVisibility(View.GONE);
        }
        atNativePrepareInfo.setAdFromView(adFromView);

        final FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(40, 10);
        layoutParams.gravity = Gravity.BOTTOM | Gravity.END;

        atNativePrepareInfo.setChoiceViewLayoutParams(layoutParams);
        atNativePrepareInfo.setClickViewList(clickViewList);

        final List<View> creativeClickViewList = new ArrayList<>();
        creativeClickViewList.add(ctaView);
        atNativePrepareInfo.setCreativeClickViewList(creativeClickViewList);
    }

    @NonNull
    @Override
    public View getSelfRenderView() {
        return selfRenderView;
    }

    private void onViewGlobalLayout(@NonNull View view, @NonNull Runnable runnable) {
        final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
        if (!viewTreeObserver.isAlive()) {
            return;
        }
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
                if (viewTreeObserver.isAlive()) {
                    viewTreeObserver.removeOnGlobalLayoutListener(this);
                }

                runnable.run();
            }
        });
    }
}